package com.example.hellodemo.datastorage;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.example.hellodemo.R;

public class SharedPreferencesActivity extends AppCompatActivity {
    private Button getBtn,saveBtn;
    private EditText editText;
    private TextView textView;
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shared_preferences);

        sharedPreferences = getSharedPreferences("data",MODE_PRIVATE);
        editor = sharedPreferences.edit();
        /*
        *    查看 data 存放
        * CodeYYdeMacBook-Pro:~ codeyy$ adb shell
generic_x86:/ $ run-as com.example.hellodemo
generic_x86:/data/data/com.example.hellodemo $ ls
cache code_cache shared_prefs
generic_x86:/data/data/com.example.hellodemo $ cd shared_prefs
generic_x86:/data/data/com.example.hellodemo/shared_prefs $ ls
data.xml
        *
        * */
        getBtn = findViewById(R.id.sharedpreference_get);
        saveBtn = findViewById(R.id.sharedpreference_save);
        editText = findViewById(R.id.sharedpreference_et);
        textView = findViewById(R.id.sharedpreference_tv);

        saveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editor.putString("name",editText.getText().toString());
                editor.apply(); // 写入内存和磁盘
            }
        });

        getBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textView.setText(sharedPreferences.getString("name",""));
            }
        });

    }
}
